<template>
  <div class="device-list">
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form
          label-width="70px"
          :inline="true"
          style="position: relative"
          class="dialog-search-form search-form-group"
        >
          <div v-show="moreSearch">
            <el-form-item label="开关状态"
              ><el-select v-model="devOnOff" placeholder="请选择">
                <el-option
                  v-for="item in FlagOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  clearable
                >
                </el-option> </el-select
            ></el-form-item>
            <el-form-item label="联网状态">
              <el-select v-model="devOnline" placeholder="请选择">
                <el-option
                  v-for="item in NetOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  clearable
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="网络状态">
              <el-select v-model="netStatusType" placeholder="请选择">
                <el-option
                  v-for="item in NetworkLockOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  clearable
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="运行模式" v-if="TempOptions.length">
              <el-select v-model="devRunMode" placeholder="请选择">
                <el-option
                  v-for="item in TempOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  clearable
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="工作状态">
              <el-select v-model="heatingType" placeholder="请选择">
                <el-option
                  v-for="item in WorkOptions"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                  clearable
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                class="btn-search"
                round
                icon="el-icon-search"
                size="medium"
                @click="initTable"
                >搜索</el-button
              >
              <el-button
                class="btn-search"
                round
                icon="el-icon-refresh"
                size="medium"
                @click="resetTable"
                >重置</el-button
              >
            </el-form-item>
          </div>
          <!-- <el-form-item style="position: absolute; top:0px;right:20px;cursor: pointer;color:#2085ea">

            <span @click="()=>{moreSearch=!moreSearch}">{{ moreSearch?'收起更多搜索':'展开更多搜索' }}</span><i :class="moreSearch?'el-icon-caret-top':'el-icon-caret-bottom'" />
          </el-form-item> -->
        </el-form>
      </card-search>
    </el-collapse-transition>

    <el-tabs style="margin: 20px" type="card" @tab-click="handleClickTab">
      <el-tab-pane
        v-for="(item, index) in devTypeList"
        :key="index"
        :label="item.dictLabel"
        :name="item.dictValue"
    /></el-tabs>
    <CardTable style="height: calc(100vh - 260px)">
      <div class="card-table-header-btns" style="margin-bottom: 20px">
        <el-button
          v-if="hasPermission('system:dnDevice:add')"
          class="btn-search"
          size="small"
          icon="el-icon-plus"
          @click="handleClick(null, 'add')"
          >新增</el-button
        >
        <el-button
          v-if="hasPermission('system:dnDevice:edit')"
          class="btn-search"
          size="small"
          icon="el-icon-edit"
          :disabled="btnDisabled"
          @click="handleClick(null, 'change')"
          >编辑</el-button
        >

        <el-button
          v-if="hasPermission('system:dnDevice:remove')"
          class="btn-search"
          size="small"
          icon="el-icon-delete"
          :disabled="btnDisabled"
          @click="handleClick(null, 'delete')"
          >删除</el-button
        >
        <!-- <el-button
          class="btn-search"
          size="small"
          icon="el-icon-download"
          v-if="isSuperAdmin || hasPermission('system:dnDevice:import')"
          >导入</el-button
        > -->
        <el-button
          class="btn-search"
          size="small"
          icon="el-icon-upload2"
          v-if="isSuperAdmin || hasPermission('system:dnDevice:export')"
          >导出</el-button
        >
        <el-button
          v-if="hasPermission('system:dnDevice:chanegGroup')"
          class="btn-search"
          size="small"
          icon="el-icon-edit"
          :disabled="btnDisabled"
          @click="handleClick(null, 'changeGroup')"
          >修改分组</el-button
        >
        <el-button
          v-if="hasPermission('system:dnDevice:batchControl')"
          class="btn-search"
          size="small"
          :disabled="btnDisabled"
          @click="handleClick(null, 'projectName')"
          ><svg-icon icon-class="control" style="margin-right: 5px"></svg-icon
          >批量控制</el-button
        >
        <el-button
          v-if="hasPermission('system:dnDevice:allTypeControl')"
          class="btn-search"
          size="small"
          @click="handleClick(null, 'projectAdmin')"
          ><svg-icon icon-class="control" style="margin-right: 5px"></svg-icon
          >全部控制</el-button
        >
        <el-input
          v-if="isSuperAdmin || hasPermission('system:dnDevice:list')"
          v-model="input"
          placeholder="请输入设备ID/名称/安装位置/备注信息"
          style="width: 330px; margin-left: 10px"
          clearable
          size="small"
          @change="initTable"
        >
          <el-button slot="append" icon="el-icon-search" @click="initTable"></el-button>
        </el-input>
        <div class="card-table-header" style="position: relative">
          <div
            class="card-table-header-actions"
            style="position: absolute; right: 0px; bottom: 0"
          >
            <table-action
              :table-header="filteredTableHeader"
              :eye-show="true"
              :search-show="hasPermission('system:dnDevice:list') || isSuperAdmin"
              @check-change="handleCheckChange"
              @search-click="handleSearchClick"
              @eye-click="handleEyeClick"
              @init-click="handleInitClick"
            />
          </div>
        </div>
      </div>
      <el-table
        v-if="eyeCardShow"
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        stripe
        size="small"
        :default-sort="{ prop: 'date', order: 'descending' }"
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
        highlight-selection-row
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-for="item in filteredTableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          :show-overflow-tooltip="true"
          :align="item.align"
          sortable
          :fixed="item.fixed"
        >
          <template #default="scope">
            <span
              v-if="item.prop === 'projectName'"
              class="link-type"
              @click="handleClick(scope.row, 'projectName')"
              ><svg-icon
                icon-class="table-edit"
                style="margin-right: 5px; width: 13px; height: 15px; fill: #165eff"
              />{{ scope.row.projectName }}</span
            >

            <span
              v-else-if="item.prop === 'projectAdmin'"
              class="link-type"
              @click="handleClick(scope.row, 'projectAdmin')"
            >
              <svg-icon
                icon-class="table-control"
                style="margin-right: 5px; width: 15px; height: 15px; fill: #165eff"
              />{{ scope.row.projectAdmin }}</span
            >
            <!-- 联网状态 -->
            <span v-else-if="item.prop === 'personInCharge'">
              <span
                :class="scope.row[item.prop] == '在线' ? 'table-online' : 'table-offline'"
              >
                {{ scope.row[item.prop] }}</span
              >
            </span>
            <!-- 开关机 -->
            <span v-else-if="item.prop === 'switchStatus'">
              <span :class="scope.row[item.prop] == '开机' ? 'table-online' : ''">
                {{ scope.row[item.prop] }}</span
              >
            </span>
            <!-- workStatus  -->
            <span v-else-if="item.prop === 'workStatus'">
              <span :class="scope.row[item.prop] == '未启动' ? '' : 'table-online'">
                {{ scope.row[item.prop] }}</span
              >
            </span>
            <span v-else>
              {{ scope.row[item.prop] }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="eye-list">
        <div v-for="(item, index) in tableData" class="eye-list-item">
          <div class="eye-list-item-left">
            <img src="https://kt.xinnuanyun.com/suittc_kt/img/kt_dev.png" alt="" />
            <div class="eye-list-item-left-template">23</div>
            <div>智能空调</div>
            <div>KT0020002022020</div>
          </div>
          <div class="eye-list-item-right">
            <div>
              <svg-icon
                icon-class="switch"
                class-name="card-panel-icon"
                style="width: 16px; height: 16px"
              />
              <span style="padding: 0 5px">开机状态:</span>
              <span class="open">开机</span>
            </div>
            <div>
              <svg-icon icon-class="rightCircle" class-name="card-panel-icon" />
              <span style="padding: 0 5px">联网状态:</span>
              <span class="close">在线</span>
            </div>
          </div>
        </div>
      </div>
      <XyPagination :total="total" @pagination="handlerPagination"></XyPagination>
    </CardTable>
    <!-- 点击设备名称弹窗  -->
    <DialogAdmin
      v-model="dialogAdminVisible"
      :rowData="rowData"
      :activeIndex="activeIndex"
      @close="handleDialogClose"
    />
    <!-- 新增弹窗 -->
    <DialogDeitail
      v-model="dialogDetailVisible"
      :field="field"
      @close="handleDialogDetailClose"
    />
    <!-- 修改批量控制弹窗 -->
    <DialogEditDevice
      v-model="dialogChangeVisible"
      @close="handleDialogChangeClose"
      :multipleSelection="multipleSelection"
    />
    <!-- 修改分组弹窗 -->
    <DialogChangeGroup
      v-model="dialogChangeGroupVisible"
      @close="handleDialogChangeGroupClose"
    />
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import XyPagination from "@/components/XyPagination";
import DialogAdmin from "@/views/DeviceManagement/DeviceList/component/DialogAdmin.vue";
import DialogDeitail from "@/views/DeviceManagement/DeviceList/component/DialogDetail.vue";
import DialogEditDevice from "@/views/DeviceManagement/DeviceList/component/DialogEditDevice.vue";
import DialogChangeGroup from "@/views/DeviceManagement/DeviceList/component/DialogChangeGroup.vue";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
import { queryDictData } from "@/api/systemmanagement";
export default {
  components: {
    CardSearch,
    CardTable,
    DialogAdmin,
    TableAction,
    DialogDeitail,
    DialogEditDevice,
    DialogChangeGroup,
    XyPagination,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      moreSearch: true,
      input: "",

      currentTabLabel: "全部类型",
      tableHeader: [
        {
          title: "项目ID",
          prop: "projectName",
          width: "130",
          visible: true,
          align: "left",
          fixed: true,
        },
        {
          title: "设备名称",
          prop: "projectAdmin",
          width: "100",
          visible: true,
          align: "left",
          fixed: true,
        },
        {
          title: "所属项目",
          prop: "company",
          width: "150",
          visible: true,
          align: "left",
        },
        {
          title: "设备分组",
          prop: "totleNum",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "设备安装位置",
          prop: "onlineNum",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "子设备类型",
          prop: "offlineNum",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "联网状态",
          prop: "personInCharge",
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "室内温度",
          prop: "address",
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "外部温度",
          prop: "outdoorTemp", // 修改为唯一值
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "开关机",
          prop: "switchStatus", // 修改为唯一值
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "目标温度",
          prop: "targetTemp", // 修改为唯一值
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "工作状态",
          prop: "workStatus", // 修改为唯一值
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "网络锁定",
          prop: "networkLock", // 修改为唯一值
          width: "150",
          visible: true,
          align: "center",
        },
        {
          title: "临时模式",
          prop: "tempMode", // 修改为唯一值
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "定时计划",
          prop: "schedule", // 修改为唯一值
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "信号强度",
          prop: "signalStrength", // 修改为唯一值
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "备注信息",
          prop: "remark", // 修改为唯一值
          visible: true,
          align: "center",
          width: "100",
        },
      ],
      tableData: [],
      multipleSelection: [],
      btnDisabled: true,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      dialogAdminVisible: false, // 详情/控制/能耗弹窗
      dialogDetailVisible: false, // 添加弹窗
      dialogChangeVisible: false, // 批量编辑弹窗
      dialogChangeGroupVisible: false, // 修改分组弹窗
      field: "",
      tableHeight: 500,
      activeIndex: 0,
      eyeCardShow: true,
      FlagOptions: [],
      NetOptions: [],
      NetworkLockOptions: [],
      TempOptions: [],
      WorkOptions: [],
      devTypeList: [],
      devOnOff: "所有", // 开关机
      devOnline: "所有", // 设备是否离线
      netStatusType: "所有", // 网络状态
      heatingType: "所有", // 工作状态
      devRunMode: "所有", // 运行模式
      devType: "所有",
      rowData: {},
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
    // 传递给table-action组件的表头数据，根据当前标签页状态过滤
    filteredTableHeader() {
      if (this.currentTabLabel !== "全部类型") {
        // 当不是"全部类型"标签页时，过滤掉"子设备类型"列
        return this.tableHeader.filter((item) => item.title !== "子设备类型");
      } else {
        // 当是"全部类型"标签页时，显示所有列
        return this.tableHeader;
      }
    },
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  props: {
    showIndex: {
      type: Number,
      default: 0,
    },
  },
  mounted() {
    this.calculateTableHeight();
    this.loadDictData("sys_sub_dev_type", "devTypeList");
    this.loadDictData("sys_switch_status", "FlagOptions");
    this.loadDictData("sys_networking_status", "NetOptions");
    this.loadDictData("sys_devKey_lock", "NetworkLockOptions");
    this.loadDictData("sys_heating_type", "WorkOptions");
    this.initTable();
  },
  methods: {
    initTable() {
      this.tableData = [
        {
          projectName: "KTWG15980001",
          projectAdmin: "智能空调1",
          company: "香缇澜山二期",
          totleNum: "-",
          onlineNum: "-",
          offlineNum: "空调交流lora",
          personInCharge: "在线",
          address: "21.9℃",
          outdoorTemp: "14.0℃",
        },
      ];
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    async loadDictData(dictType, targetProperty) {
      try {
        // 调用 store 中的字典查询方法，传入字典类型
        const data = await this.$store.dispatch("dict/queryDictData", dictType);
        // 根据接口返回的数据格式进行处理
        if (dictType == "sys_sub_dev_type") {
          this[targetProperty] = [{ dictLabel: "全部类型", dictValue: "" }, ...data];
        } else {
          this[targetProperty] = [{ dictLabel: "所有", dictValue: "" }, ...data];
        }
      } catch (error) {
        this.$message.error("获取数据失败");
      }
    },
    resetTable() {
      this.devOnOff = "所有"; // 开关机
      this.devOnline = "所有"; // 设备是否离线
      this.netStatusType = "所有"; // 网络状态
      this.heatingType = "所有"; // 工作状态
      this.devRunMode = "所有"; // 运行模式
      this.initTable();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
    },
    handleClick(row, field) {
      switch (field) {
        case "projectName":
          this.dialogAdminVisible = true;
          this.rowData = row;
          this.activeIndex = 0;
          break;
        case "projectAdmin":
          if (row.personInCharge == "离线") {
            this.$message({
              type: "warning",
              message: "设备已离线,无法操作!",
            });
            return;
          }
          this.dialogAdminVisible = true;
          this.rowData = row;
          this.activeIndex = 1;
          break;
        case "add":
          this.dialogDetailVisible = true;
          this.field = "add";
          break;
        case "change":
          this.dialogChangeVisible = true;
          break;

        case "changeGroup":
          this.dialogChangeGroupVisible = true;
          this.field = "changeGroup";
          break;
        case "delete":
          this.$confirm(
            `确认删除选中的${this.multipleSelection.length}个设备吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
          break;
        default:
          break;
      }
    },
    handleClickTab(tab, event) {
      console.log(tab);
      this.devRunMode = "所有";
      this.currentTabLabel = tab.label;
      // 更新表格显示（如果需要根据标签类型过滤数据，可以在这里处理）
      this.tableKey += 1;
      if (tab.name) {
        this.devType = tab.name;
        this.loadDictData(`sys_devMode_${this.devType}`, "TempOptions"); // 运行模式  根据devType决定
      } else {
        this.devType = "";
        this.TempOptions = [];
      }

      this.initTable();
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        // 对于"子设备类型"列，需要考虑当前标签页状态
        if (item.title === "子设备类型") {
          // 如果是"全部类型"标签页，则根据用户选择决定是否显示
          // 如果是其他标签页，则始终隐藏
          if (this.currentTabLabel === "全部类型") {
            item.visible = checkedValues.includes(item.prop);
          } else {
            item.visible = false;
          }
        } else {
          // 其他列按正常逻辑处理
          item.visible = checkedValues.includes(item.prop);
        }
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleEyeClick() {
      this.eyeCardShow = !this.eyeCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    handleDialogClose() {
      this.field = "";
      this.activeIndex = -1;
      this.dialogAdminVisible = false;
    },
    handleDialogDetailClose() {
      this.field = "";
      this.dialogDetailVisible = false;
    },
    handleDialogChangeClose() {
      this.dialogChangeVisible = false;
    },
    handleDialogChangeGroupClose() {
      this.dialogChangeGroupVisible = false;
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 130; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.eye-list {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20px;
  .eye-list-item {
    border: 1px solid #e7eaec;
    padding: 20px;
    display: flex;
    color: #676a6c;
    font-size: 13px;
    .eye-list-item-left {
      position: relative;
      img {
        width: 130px;
        height: 130px;
      }
      .eye-list-item-left-template {
        position: absolute;
        top: 42px;
        left: 42px;
        font-size: 34px;
        font-weight: bold;
      }
      div {
        line-height: 24px;
        text-align: center;
        font-weight: bold;
      }
    }
    .eye-list-item-right {
      margin-top: 30px;
      margin-left: 10px;
      font-size: 14px;
      line-height: 26px;
      .open {
        color: #fff;
        background: #1ab394;
        border-radius: 10px;
        font-weight: bold;
        font-size: 12px;
        padding: 2px 4px;
      }
      .close {
        color: #fff;
        background: #ed556e;
        border-radius: 10px;
        font-weight: bold;
        font-size: 12px;
        padding: 2px 4px;
      }
    }
  }
}
</style>
<style lang="scss">
.search-form-group.dialog-search-form.el-form {
  .el-form-item {
    .el-form-item__content {
      margin-left: 0 !important;
    }
    .el-select {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
    }
  }
}
</style>
